package com.xiongwei.io;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * Reader定义了所有字符输入流的超类:
 *      FileReader实现了文件字符流输入,使用时需要指定编码;
 *      CharArrayReader和StringReader可以在内存中模拟一个字符流输入
 *
 * Reader是基于InputStream构造的,可以通过InputStreamReader在编码的同时将任何InputStream转换为Reader
 *
 * @author XiongWei
 * @date 2021/1/8
 */
public class ReaderUse {

    public static void main(String[] args) {
        ReaderUse ru = new ReaderUse();
        ru.test();
        ru.testReaderMore();
        ru.testCharArrayReader();
        ru.testStringReader();
    }

    public void test() {
        //编译器会自动为我们写入finally并调用close()
        try(Reader reader = new FileReader("src/com/xiongwei/io/readme.txt", StandardCharsets.UTF_8)){
            int n;
            while ((n = reader.read()) != -1) {
                System.out.print((char)n);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void testReaderMore() {
        try (Reader reader = new FileReader("src/com/xiongwei/io/readme.txt", StandardCharsets.UTF_8)) {
            char[] buffer = new char[1000];
            int n;
            while ((n = reader.read(buffer)) != -1) {
                System.out.println("read " + n + " chars.");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void testCharArrayReader() {
        try (Reader reader = new CharArrayReader("HELLO".toCharArray())) {
            int n;
            while ((n = reader.read()) != -1) {
                System.out.print((char) n);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void testStringReader() {
        try (Reader reader = new StringReader("world")) {
            int n;
            while ((n = reader.read()) != -1) {
                System.out.print((char) n);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
